package com.zhitan.ems.app.stat.config.controller;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.app.stat.config.entity.ElectricityTypeSettingEntity;
import com.zhitan.ems.app.stat.config.entity.ElectricityTypeSettingItemEntity;
import com.zhitan.ems.app.stat.config.service.ElectricityTypeSettingItemService;
import com.zhitan.ems.app.stat.config.util.ElectricityCalculationUtil;
import com.zhitan.ems.app.stat.config.vo.ElectricityTypeSettingItemVO;
import com.zhitan.ems.app.stat.config.vo.ElectricityTypeSettingVO;
import com.zhitan.ems.app.stat.config.wrapper.ElectricityTypeSettingItemWrapper;
import com.zhitan.ems.app.stat.config.wrapper.ElectricityTypeSettingWrapper;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.common.utils.poi.ExcelUtil;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 点峰平谷配置项
 * @author zhitan
 * 
 * @date 2025-09-20 09:56:55
 */
@Api(tags = "点峰平谷配置项", value = "点峰平谷配置项")
@RestController
@RequestMapping("intra/config/electricitytypesettingitem")
public class ElectricityTypeSettingItemController extends BaseController{
    @Autowired
    private ElectricityTypeSettingItemService electricityTypeSettingItemService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browse")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:list')")
    public R<VPage<ElectricityTypeSettingItemVO>> browse(@RequestParam Map<String, Object> params){
        QueryWrapper<ElectricityTypeSettingItemEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), ElectricityTypeSettingItemEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        IPage<ElectricityTypeSettingItemEntity> pages = electricityTypeSettingItemService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(ElectricityTypeSettingItemWrapper.build().toVPageVO(pages));
    }
    @ApiOperation(value = "列表所有", response = VPage.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
    })
    @GetMapping("/listAll")
    @PreAuthorize("@ss.hasPermi('iot:devicetype:list')")
    public R<List<ElectricityTypeSettingItemVO>> listAll(@RequestParam Map<String, Object> params){
    	QueryWrapper<ElectricityTypeSettingItemEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), ElectricityTypeSettingItemEntity.class);
    	queryWrapper.orderByDesc("id");
    	queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
    	List<ElectricityTypeSettingItemEntity> pages = electricityTypeSettingItemService.list( queryWrapper);
    	return R.data(ElectricityTypeSettingItemWrapper.build().listVO(pages));
    }
    @GetMapping("/listStat")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:list')")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<ElectricityTypeSettingItemEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), ElectricityTypeSettingItemEntity.class);
         queryWrapper.select("count(id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=electricityTypeSettingItemService.getMap(queryWrapper);
        return R.data(stat);
    }
    @ApiOperation("导出")
	@Log(title = "参数管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:list')")
	@PostMapping("/toExport")
	public void toExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
		QueryWrapper<ElectricityTypeSettingItemEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				ElectricityTypeSettingItemEntity.class);
		queryWrapper.orderByDesc("id");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "name", params.get("name"));
		 List<ElectricityTypeSettingItemEntity> electricityTypeSettingItemList = electricityTypeSettingItemService.list(queryWrapper);
		ExcelUtil<ElectricityTypeSettingItemEntity> util = new ExcelUtil<>(ElectricityTypeSettingItemEntity.class);
		util.exportExcel(response, electricityTypeSettingItemList, "参数数据");
	}
   
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = ElectricityTypeSettingItemVO.class)
    @GetMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:info')")
    public R<ElectricityTypeSettingItemVO> detail(@PathVariable("id") Long id){
		ElectricityTypeSettingItemEntity electricityTypeSettingItem = electricityTypeSettingItemService.getById(id);
	    return R.data(ElectricityTypeSettingItemWrapper.build().entityVO(electricityTypeSettingItem));
    }
    
    @Log(title = "电峰平谷配置", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submitBatch")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:save')")
    public R<Boolean> submitBatch(@Valid @RequestBody List<ElectricityTypeSettingItemVO> electricityTypeSettingList){
    	for(ElectricityTypeSettingItemVO item:electricityTypeSettingList) {
    		submit(item);
    	}
    	 return R.ok();
    }
     /**
     * 保存&更新 
     */
    @Log(title = "点峰平谷配置项", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:save')")
    public R<ElectricityTypeSettingItemVO> submit(@Valid @RequestBody ElectricityTypeSettingItemVO electricityTypeSettingItem){
    	 if(electricityTypeSettingItem.getId()==null) {
           return add(electricityTypeSettingItem);
         }else {
           return edit(electricityTypeSettingItem);
        }
    }
    
    @Log(title = "点峰平谷配置项", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:save')")
    public R<ElectricityTypeSettingItemVO> add(@Valid @RequestBody ElectricityTypeSettingItemVO electricityTypeSettingItem){
   		if(electricityTypeSettingItem.getId()==null) {
            electricityTypeSettingItem.setCreateAt(new Date());
            electricityTypeSettingItem.setIsDelete(0);
            electricityTypeSettingItem.setUpdateAt(new Date());
        } 
   		List<ElectricityTypeSettingItemEntity> curAllItemList=electricityTypeSettingItemService.getBySettingId(electricityTypeSettingItem.getSettingId());
   		boolean flag=false;
   		for(ElectricityTypeSettingItemEntity item:curAllItemList) {
   			if(electricityTypeSettingItem.getId()!=null&&item.getId()==electricityTypeSettingItem.getId()) {
   				continue;
			 }
   			 if(ElectricityCalculationUtil.isTimeInRange(electricityTypeSettingItem.getStartTime(), item.getStartTime(), item.getEndTime())) {
   				 flag=true;
   				 break;
   			 }
   			if(ElectricityCalculationUtil.isTimeInRange(electricityTypeSettingItem.getStartTime(), item.getStartTime(), item.getEndTime())) {
   				flag=true;
   				break;
   			 }
   		}
   		if(flag) {
   			return R.error("时间重复！");	
   		}
    	if(electricityTypeSettingItemService.save(electricityTypeSettingItem)) {
    		 return R.ok(electricityTypeSettingItem);
    	 }
    	return R.error("数据错误");
    }
    
    @Log(title = "点峰平谷配置项", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:update')")
    public R<ElectricityTypeSettingItemVO> edit(@Valid @RequestBody ElectricityTypeSettingItemVO electricityTypeSettingItem){
   		electricityTypeSettingItem.setUpdateAt(new Date());
   		List<ElectricityTypeSettingItemEntity> curAllItemList=electricityTypeSettingItemService.getBySettingId(electricityTypeSettingItem.getSettingId());
   		boolean flag=false;
   		for(ElectricityTypeSettingItemEntity item:curAllItemList) {
   			if(electricityTypeSettingItem.getId()!=null&&item.getId()==electricityTypeSettingItem.getId()) {
   				continue;
			 }
   			 if(ElectricityCalculationUtil.isTimeInRange(electricityTypeSettingItem.getStartTime(), item.getStartTime(), item.getEndTime())) {
   				 flag=true;
   				 break;
   			 }
   			if(ElectricityCalculationUtil.isTimeInRange(electricityTypeSettingItem.getEndTime(), item.getStartTime(), item.getEndTime())) {
   				flag=true;
   				break;
   			 }
   		}
   		if(flag) {
   			return R.error("时间重复！");	
   		}
    	if(electricityTypeSettingItemService.updateById(electricityTypeSettingItem)) {
    		 return R.ok(electricityTypeSettingItem);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('config:electricitytypesettingitem:delete')")
    @Log(title = "点峰平谷配置项", businessType = BusinessType.DELETE)
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(electricityTypeSettingItemService.removeByIds(Arrays.asList(ids)));
    }

}
